// pages/previewVisit/previewVisit1.js
const requestUtil = require('../../../../utils/requestUtil')
Page({
  // showModal: true ,
  // onAgreeClick: function() {
  //   this.setData({ showModal: false });
  // },

  // 验证函数
  validateName: function (name) {
    const reg = /^[a-zA-Z\u4e00-\u9fa5]{1,20}$/;
    return reg.test(name);
  },
  validateID: function (id) {
    const reg = /^[1-9]\d{5}(18|19|20)?\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[\dX]$/;
    return reg.test(id);
  },
  validateCarPlate: function (carPlate) {
    const reg = /^[\u4e00-\u9fa5]{1}[A-Z]{1}[A-Z0-9]{4,6}$/;
    return reg.test(carPlate);
  },



  showAnnouncement: function () {
    this.setData({
      flag: false,
    });
  },
  closeAnnouncement: function () {
    this.setData({
      flag: true,
    })
  },
  blackAnnouncement: function () {
    // this.setData({
    //   flag: true,
    // }),
    wx.navigateBack({
      url: '/pages/previewVisit/previewVisit'
    });

  },

  data: {
    IdCount: 0,
    NameCount: 0,
    list: [{
      name: '',
      id: '',
      car: ''
    }, ],
    //wjl
    //选择的时间段 起始值
    slotId: 0,
    //预约哪一天
    appointmentDate: "",
    //各个信息
    details: [],
    //提前天数
    daysAhead: "",
    //
    flag: true, //控制弹窗显示
    showDetails: true, // 控制姓名、身份证号和车辆信息的显示

    dates: [
      // { day: '周一', date: '11月18日', remaining: '余30人', selected: false },
      // { day: '周二', date: '11月19日', remaining: '余30人', selected: false },
      // { day: '周三', date: '11月20日', remaining: '余30人', selected: false },
      // { day: '周四', date: '11月21日', remaining: '余30人', selected: false },
      // { day: '周五', date: '11月22日', remaining: '余30人', selected: false },
      // { day: '周六', date: '11月23日', remaining: '余30人', selected: false },
      // { day: '周日', date: '11月24日', remaining: '余30人', selected: false }
    ],
    selectedDate: '',
    selectedCount: 0,
    timeRanges: ['8:00-10:00', '10:00-12:00', '12:00-14:00', '14:00-16:00', '16:00-18:00', ],
    timeIndex: 0,
    selectedTime: '15',
    name: '',
    id: '',
    car: '',
    // totalPeople: 0, 
    peopleCount: 1, // 新增变量来存储已填写的人员数量
  },
  postBookData() {
    wx.showLoading({
      title: 'Loading...',
    })
    //日
    if (parseInt(this.data.appointmentDate.split('-')[2]) < 10) {
      let parts = this.data.appointmentDate.split('-');
      parts[2] = parts[2].padStart(2, '0');
      this.setData({
        appointmentDate: parts.join('-')
      })
    }
    //月
    if (parseInt(this.data.appointmentDate.split('-')[1]) < 10 &&this.data.appointmentDate.split('-')[1].charAt(0) != '0') {
      let parts = this.data.appointmentDate.split('-');
      parts[1] = parts[1].padStart(2, '0');
      this.setData({
        appointmentDate: parts.join('-')
      })
    }
    const data = {
      "slotId": this.data.slotId,
      "appointmentDate": this.data.appointmentDate,
      "details": this.data.details,
      "daysAhead": this.data.daysAhead
    }
    requestUtil.requestRe('appointment/create', 'Post', data)
      .then((responseData) => {
        this.setData({
          details: []
        })
        wx.showToast({
          title: '预约成功',
        })
        wx.navigateTo({
          url: '/packageBook/pages/appointHistory/appointHistory',
        })
      })
      .catch((error) => {
        wx.showModal({
          title: '添加失败',
          content: error.msg
        })
      });
  },
  //  删除
  delete(e) {
    let index = e.currentTarget.dataset.index;
    let list = this.data.list;
    list.splice(index, 1);
    this.setData({
      list,
      peopleCount: this.data.peopleCount - 1, // 更新totalPeople
    })
  },
  onLoad: function () {
    this.generateDates();
    this.setData({
      totalPeople: this.data.list.length,
    });
  },
  generateDates: function () {
    const today = new Date();
    const dates = [];
    for (let i = 0; i < 7; i++) {
      const day = today.getDay();
      const date = new Date(today.getFullYear(), today.getMonth(), today.getDate() + i);
      const dayName = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()];
      const formattedDate = `${date.getMonth() + 1}月${date.getDate()}日`;
      dates.push({
        day: dayName,
        date: formattedDate,
        // remaining: '余30人',
        selected: false,
      });
    }
    this.setData({
      dates
    });
  },
  // 单人预约数据输入
  onNameInput: function (e) {
    const name = e.detail.value;
    if (!this.validateName(name)) {
      // wx.showToast({
      //   title: '姓名格式不正确',
      //   icon: 'none'
      // });
      // this.updatePersonInfo(e);
      const index = e.currentTarget.dataset.index;
      const list = this.data.list;
      list[index].name = name;
      this.setData({
        list
      });
      return;
    } else {
      this.data.NameCount = 1;
      // this.updatePersonInfo(e);
      const index = e.currentTarget.dataset.index;
      const list = this.data.list;
      list[index].name = name;
      this.setData({
        list
      });
    }
  },
  onIDInput: function (e) {
    const id = e.detail.value;
    if (!this.validateID(id)) {
      // wx.showToast({
      //   title: '身份证号格式不正确',
      //   icon: 'none'
      // });
      // this.updatePersonInfo(e);
      const index = e.currentTarget.dataset.index;
      const list = this.data.list;
      list[index].id = id;
      this.setData({
        list
      });
      return;
    } else {
      this.data.IdCount = 1
      // this.updatePersonInfo(e);
      const index = e.currentTarget.dataset.index;
      const list = this.data.list;
      list[index].id = id;
      this.setData({
        list
      });
    }
  },
  onCarInput: function (e) {
    const carPlate = e.detail.value;
    if (!this.validateCarPlate(carPlate)) {
      // wx.showToast({
      //   title: '车牌号格式不正确',
      //   icon: 'none'
      // });
      // return;
      // this.updatePersonInfo(e);
      const index = e.currentTarget.dataset.index;
      const list = this.data.list;
      list[index].car = carPlate;
      this.setData({
        list
      });
    } else {
      // this.updatePersonInfo(e);
      const index = e.currentTarget.dataset.index;
      const list = this.data.list;
      list[index].car = carPlate;
      this.setData({
        list
      });
    }
  },

  updatePersonInfo: function (e) {
    const index = e.currentTarget.dataset.index;
    const list = this.data.list;
    list[index][e.currentTarget.dataset.type] = e.detail.value; // 更新对应的信息
    this.setData({
      list,
      // peopleCount: this.data.list.length 
    });
  },
  calculatePeopleCount: function () {
    // 计算已填写的人员数量
    return this.data.list.reduce((count, person) => {
      return count + (person.name && person.id && person.car ? 1 : 0);
    }, 0);
  },
  addPerson: function () {
    const newPerson = {
      name: '',
      id: '',
      car: ''
    };

    this.setData({
      peopleCount: this.data.peopleCount + 1
    })
    this.setData({
      list: [...this.data.list, newPerson],
      totalPeople: this.data.list.length++, // 更新totalPeople
    });
  },
  onTimeChange: function (e) {
    this.setData({
      timeIndex: e.detail.value,
      selectedTime: this.data.timeRanges[e.detail.value]
    });
  },
  selectDate: function (e) {
    const {
      date
    } = e.currentTarget.dataset;
    const index = this.data.dates.findIndex(item => item.date === date);

    const updatedDates = this.data.dates.map(item => ({
      ...item,
      selected: item.date === date
    }));

    this.setData({
      dates: updatedDates,
      selectedDate: date,
      // selectedCount: parseInt(updatedDates.find(item => item.selected).remaining.replace('余', ''), 10),
      daysAhead: index // 使用索引作为天数差
    });
  },
  onConfirm: function () {
    if (!this.data.selectedDate) {
      wx.showToast({
        title: '请选择参观日期',
        icon: 'none'
      });
    } else if (!this.data.name || !this.data.id || !this.data.selectedTime) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
    } else {
      // 确认按钮事件处理
      console.log('姓名：', this.data.name);
      console.log('身份证号：', this.data.id);
      console.log('车辆信息：', this.data.car);
      console.log('选择日期：', this.data.selectedDate);
      console.log('入校时间：', this.data.selectedTime);
    }
  },
  onReset: function () {
    // 重置按钮事件处理
    this.setData({
      name: '',
      id: '',
      car: '',
      selectedTime: '15',
      selectedDate: '',
      selectedCount: 0,
      dates: this.data.dates.map(item => ({
        ...item,
        selected: false
      }))
    });
  },
  onBookNow: function () {

    // 检查是否选择了参观日期
    if (!this.data.selectedDate) {
      wx.showToast({
        title: '请选择参观日期',
        icon: 'none'
      });
      return;
    }

    if (this.data.selectedTime === '15') { // 默认值，表示没有选择
      wx.showToast({
        title: '请选择预约入校时间段',
        icon: 'none'
      });
      return;
    }

    if (!this.data.NameCount) {
      wx.showToast({
        title: '姓名格式不正确',
        icon: 'none'
      });
      return;
    }
    if (!this.data.IdCount) {
      wx.showToast({
        title: '身份证格式不正确',
        icon: 'none'
      });
      return;
    }

    for (let i = 0; i < this.data.list.length; i++) {
      const person = this.data.list[i];
      // 检查姓名格式
      if (!person.name || !this.validateName(person.name)) {
        wx.showToast({
          title: `第${i + 1}个人员的姓名格式不正确`,
          icon: 'none'
        });
        return; // 一旦找到格式不正确的姓名，立即退出函数
      }
      // 检查身份证号格式
      if (!person.id || !this.validateID(person.id)) {
        wx.showToast({
          title: `第${i + 1}个人员的身份证格式不正确`,
          icon: 'none'
        });
        return; // 一旦找到格式不正确的身份证号，立即退出函数
      }
    }


    // 检查list中的每个对象是否都包含name、id
    const isListComplete = this.data.list.every(person => {
      return person.name && person.id;
    });

    if (!isListComplete) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    // 如果list完整，继续处理预约逻辑
    const dateParts = this.data.selectedDate.match(/\d+/g);
    if (dateParts && dateParts.length === 2) {
      // 获取当前年份
      let currentYear = new Date().getFullYear();
      // console.log('预约月份'+`${dateParts[0]}`)
      if (`${dateParts[0]}` == '1') {
        //是预约的1月份 但是当前是12月 所以年份加1
        if (new Date().getMonth() == 11) {
          currentYear+=1
        }
      }
      // 格式化日期为“2024-11-19”的形式350622200202263333
      const formattedDate = `${currentYear}-${dateParts[0]}-${dateParts[1]}`;

      
     
      // 创建一个新的details数组，并添加当前信息
      const newDetails = this.data.list.map((person) => {
        return {
          name: person.name,
          idNumber: person.id,
          carId: person.car
        };
      });

      // 将新的details数组设置到data中
      this.setData({

        slotId: this.data.timeIndex, // 将timeIndex的值设置给slotId
        appointmentDate: formattedDate // 将formattedDate的值设置给appointmentDate
      });
      //判断预约时间350124200407022934
      const nowTime = new Date();
      // console.log('sssssssssssss'+nowTime.getDate())
      // console.log('s2s2s2s2s2'+this.data.appointmentDate.split('-')[2])
      // if(this.data.appointmentDate.split('-')[2] == nowTime.getDate()){
      //   console.log(1110000)
      // }
      if (this.data.appointmentDate.split('-')[2] == nowTime.getDate()) {
        if (this.data.slotId == 0) {
          console.log(111111111111111111111111111111111111111111111111111111111111)
          if (nowTime.getHours() > 10) {
            console.log(11111111111111111111111)
            wx.showToast({
              title: '该时段已不可预约',
              icon: 'none'
            })
            return
          }
        } else if (this.data.slotId == 1) {
          if (nowTime.getHours() > 12) {
            wx.showToast({
              title: '该时段已不可预约',
              icon: 'none'
            })
            return
          }
        } else if (this.data.slotId == 2) {
          if (nowTime.getHours() > 14) {
            wx.showToast({
              title: '该时段已不可预约',
              icon: 'none'
            })
            return
          }
        } else if (this.data.slotId == 3) {
          if (nowTime.getHours() > 16) {
            wx.showToast({
              title: '该时段已不可预约',
              icon: 'none'
            })
            return
          }
        } else if (this.data.slotId == 4) {
          console.log('开始判断' + this.data.slotId)
          if (nowTime.getHours() >= 18) {
            wx.showToast({
              title: '该时段已不可预约',
              icon: 'none'
            })
            return
          }
        }
      }
      // 测试提交
      //           console.log(1111)
      //           console.log(this.data.slotId)
      //           console.log(this.data.appointmentDate)
      //           console.log(this.data.details)
      //           console.log(this.data.daysAhead)
      this.setData({
        details: [...this.data.details, ...newDetails]
      })
      // 提交数据到后台
      console.log('提交数据：', {
        name: this.data.name,
        id: this.data.id,
        car: this.data.car,
        date: this.data.selectedDate,
        time: this.data.selectedTime,
        slotId: this.data.timeIndex, // 使用timeIndex作为slotId的值
        appointmentDate: this.data.appointmentDate, // 使用formattedDate作为appointmentDate的值
        details: this.data.details
      });
      this.postBookData()
      // 打印timeIndex和appointmentDate
      console.log('timeIndex:', this.data.timeIndex); // 使用timeIndex代替slotId
      console.log('appointmentDate:', this.data.appointmentDate); // 使用formattedDate作为appointmentDate的值

      // 打印details数组中的每个元素
      console.log('details:');
      this.data.details.forEach((detail, index) => {
        console.log(`details[${index}]:`, detail);
      });

      // 打印daysAhead
      console.log('daysAhead:', this.data.daysAhead);
      console.log('list:', this.data.list);

      // 重置peopleList便下一次预约
      this.setData({
        peopleList: [],
        list: [{
          name: '',
          id: '',
          car: ''
        }, ],
        peopleCount: 1


      });
    } else {
      wx.showToast({
        title: '日期格式不正确',
        icon: 'none'
      });
    }

  },



});